//
//  HMConsultingRoom.swift
//  HealthMonitoring
//
//  Created by YTYanK on 2018/8/27.
//  Copyright © 2018年 YTYanK. All rights reserved.
//  诊室页面

import UIKit
import SwiftyJSON


class HMConsultingRoom: HMViewController {
    
    let icon1 = homeIconView()
    let icon2 = homeIconView()
    let bgImageView = UIImageView()
    var roomList = Array<Any>()
    private lazy var table: UITableView = {
        let _table = UITableView()
        return _table
    }()
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        //医生获取健康咨询列表
        NetRequestTool.shareInstance.met = .get
        NetRequestTool.request(url: "doctor/consult/list", parameters: [:], success: { (json) in
            print("====>>", json)
            let code = json["code"].intValue
            if code == 0 {
                
                self.roomList = json["data"].arrayValue
                self.table.reloadData()
                self.table.isHidden = false
            }else {
                //其他错误
                self.table.isHidden = true
            }
            
            
        }, fail: { (code, err) in
            print("=====>",code, err)
        }) {
            
        }
        
    }
    
    override func setupView() {
        
        self.title = "医生出诊"
        view.backgroundColor = configure.shareConfigure.HMColor2
        view.addSubview(icon1)
        view.addSubview(icon2)
        view.addSubview(table)
      
        
        icon1.leadingAlign(view: view, predicate: "0")
        icon1.topAlign(view: view)
        icon1.setData(imgName: "weiBo", title: "医生论坛")
        icon1.tag = 1110
        icon1.delegate = self //as! homeIconViewDelegate
        icon1.heightConstrain(predicate: "120")
        icon1.width(view: view, predicate: "*0.5")
        icon1.addLayer(isAddLayer: (false, false, true, false), color: UIColor.gray, crude: 1, layout: (w: (view.wWidth/2), h:120))
        
        icon2.leadingHorizontally(view: icon1, predicate: "0")
        icon2.topAlign(view: view)
        icon2.setData(imgName: "weiBo", title: "档案管理")
        icon2.tag = 1111
        icon2.delegate = self
        icon2.heightConstrain(predicate: "120")
        icon2.width(view: view, predicate: "*0.5")
        
        
        table.delegate = self
        table.dataSource = self
        table.topVertically(view: icon1, predicate: "\(10)")
        let h = view.wHeight - 120
        table.heightConstrain(predicate: "\(h)")
        table.leadingAlign(view: view, predicate: "0")
        table.trailingAlign(view: view, predicate: "0")
        table.register(HMSessionCell.classForCoder(), forCellReuseIdentifier: "HMSessionCell")

        bgImageView.image = UIImage.init(named: "list_null")
        bgImageView.centerXYAlign(view: view)
    }
    
}


extension HMConsultingRoom : UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.roomList.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return  88
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = table.dequeueReusableCell(withIdentifier: "HMSessionCell") as! HMSessionCell
        
        cell.setJson(json: self.roomList[indexPath.row] as! JSON)
//        cell.setIMData(data: (self.roomList[indexPath.row] as! TIMConversation))
        cell.iconBlock = {
            (sessionCell) -> () in
            let patient = HMPatient()
            patient.dataJson =  (self.roomList[indexPath.row] as! JSON)
            patient.navigationController?.navigationBar.backgroundColor = .red
            self.pushViewController(patient)
        }
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
       // let cell = tableView.cellForRow(at: indexPath) as! HMSessionCell
        
        let cell = tableView.cellForRow(at: indexPath) as! HMSessionCell
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        let _im : InstantMessaging = storyBoard.instantiateViewController(withIdentifier: "IM") as! InstantMessaging
        
        // 拿到对应的会话
        let dic = self.roomList[indexPath.row] as! JSON
        let userIdStr = dic["userId"].stringValue
        
        let con :TIMConversation =   HMPlatform.getSomeoneConversation(userIdStr)
        _im.conversation = con
        _im.im_userId = con.getReceiver()
        _im.userProfile = dic
        _im.im_consultId =  dic["consultId"].stringValue
        if cell.userProfile != nil {
            _im.doctorProfile = cell.userProfile!
        }
        _im.dataAry =   con.getLastMsgs(20)   //cell.messageList!
        self.pushViewController(_im)
        
    }
    
    
    
}


extension HMConsultingRoom: homeIconViewDelegate {
    func viewTapClick(view: UIView) {
        if view.tag == 1111 {
            // 进入医生诊室
            let drug = HMProposalDrug()
            drug.info = ["sign": "档案管理"]
            drug.title = "档案管理"
            
            drug.variableTitles = ["药方管理", "咨询设置"]
            let twoVc = HMProposalAll()
            twoVc._signStr = "医生出诊"
            twoVc.titleSign = "医生出诊"
            let threeVc = HMAdvisorySetting()
            drug.variableControllers = [twoVc, threeVc]
            
            
            //            let oneVc  = HMQuickQuestion()  // 这个模版先不用
            //            oneVc._signStr = "xxxx1"
            self.pushViewController(drug)
        }else {
            // 进入论坛
//            let health  = HMHealthCounseling()
//            self.pushViewController(health)
        }
    }
}

extension HMConsultingRoom: HMSessionCellDelegate {
    
    func sessionCellBtn(sender: UIButton, doctor: Bool) {
//        print("======>>", sender.dictionary)
        
        let conId = sender.dictionary!["consultId"] as! String
    
        //医生邀请健康咨询
        NetRequestTool.shareInstance.met = .post
        NetRequestTool.request(url: "doctor/consult/invite", parameters: ["consultId": conId], success: { (json) in
            print("====>>", json)
            let code = json["code"].intValue
            if code == 0 {
                 self.showToast(message: "邀请成功")
            }else {
                //其他错误
            }
            
            
        }, fail: { (code, err) in
            print("=====>",code, err)
        }) {
            
        }
        
        
        
//        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
//        let _im : InstantMessaging = storyBoard.instantiateViewController(withIdentifier: "IM") as! InstantMessaging
//        self.pushViewController(_im)
    }
    
}

